//
//  MediaComponent.m
//  XYLib
//
//  Created by Richard on 2018/4/13.
//  Copyright © 2018年 XYLib. All rights reserved.
//

#import "MediaComponent.h"
#import <WeexSDK/WXDefine.h>
#import "WXSDKManager.h"
#import <WeexSDK/WeexSDK.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "Reachability.h"

@interface MediaComponent()
@property (nonatomic, strong) MPVolumeView *mpVolumeView;
@property (nonatomic, strong) UISlider *volumeSlider;
@property (nonatomic,assign)  float volumeValue;
@property (nonatomic, strong) NodePlayer *np;
@property (nonatomic, strong) NSString *videoURL;
@property (nonatomic, strong) NSString *posterURL;
@property (nonatomic) BOOL autoPlay;
@property (nonatomic) BOOL playStatus;
@property (nonatomic) BOOL screenKeep;

@property (strong, nonatomic) Reachability *hostReachability;
@end

@implementation MediaComponent

WX_EXPORT_METHOD(@selector(rotationLive))
WX_EXPORT_METHOD(@selector(disableSound:))
WX_EXPORT_METHOD(@selector(setVideoEnable:))
WX_EXPORT_METHOD(@selector(volume:))
WX_EXPORT_METHOD(@selector(refresh))

-(void)disableSound:(BOOL)disable{
    if (disable) {
        [_volumeSlider setValue:0];
    }else{
        if (_volumeValue<=0) {
            _volumeValue = 0.6;
            [_volumeSlider setValue:_volumeValue];
        }else{
            [_volumeSlider setValue:_volumeValue];
        }
    }
}

-(void)setVideoEnable:(BOOL)enable{
    if (_np) {
        [_np setVideoEnable:enable];
    }
}

-(void)volume:(float)volume{
    if(volume>=1.0){
        [_volumeSlider setValue:1.0];
    }else if(volume <=0){
        [_volumeSlider setValue:0];
    }else{
        [_volumeSlider setValue:_volumeValue];
    }
}

-(void)rotationLive{
    
}

-(void)refresh{
    if (_videoURL && _videoURL.length>0) {
        [_np setInputUrl:_videoURL];
        [_np start];
    }

}

- (instancetype)initWithRef:(NSString *)ref type:(NSString *)type styles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance *)weexInstance {
    self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance];
    if (self) {
        if (attributes[@"src"]) {
            _videoURL = attributes[@"src"];
        }
        if (attributes[@"autoPlay"]) {
            _autoPlay = [attributes[@"autoPlay"] boolValue];
        }
        if ([attributes[@"playStatus"] compare:@"play" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            _playStatus = true;
        }
        if ([attributes[@"playStatus"] compare:@"pause" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
            _playStatus = false;
        }
        if (attributes[@"poster"]) {
            _posterURL = attributes[@"poster"];
        }
        
        if (attributes[@"screenKeepOn"]) {
            _screenKeep = [attributes[@"screenKeepOn"] boolValue];
        }
    }
    return self;
}
-(void)controlVolume{
    
    _mpVolumeView = [[MPVolumeView alloc]init];
    
    _mpVolumeView.showsRouteButton = NO;
    //默认YES，这里为了突出，故意设置一遍
    _mpVolumeView.showsVolumeSlider = NO;
    
    [_mpVolumeView sizeToFit];
//    [_mpVolumeView setFrame:CGRectMake(-1000, -1000, 10, 10)];
    
    [self.view addSubview:_mpVolumeView];
    [_mpVolumeView userActivity];
    
    for (UIView *view in [_mpVolumeView subviews]){
        if ([[view.class description] isEqualToString:@"MPVolumeSlider"]){
            _volumeSlider = (UISlider*)view;
            break;
        }
    }
    
    //获取最是刚打开时的音量值
    _volumeValue = [[AVAudioSession sharedInstance] outputVolume];
//    if (_volumeValue) {
//        [_volumeSlider setValue:_volumeValue];
//    }
}

-(void)initPlayer{
    _np = [[NodePlayer alloc ] initWithPremium:@"W4hUJuvX60T3yOfFkFpE3OGMVfiDgfBfaZCQ0SJ5V0pi95FnbR+MK5VdjeldTpMC5VdNH2cQnQUzkrR35+PNMA=="];
    [_np setNodePlayerDelegate:self];//设置事件代理
    [_np setBufferTime:300];//设置首屏启动缓冲时长,不是实际等待时间,而是缓冲区存放的时长,建议100-500毫秒
    [_np setMaxBufferTime:1000];//设置缓冲区最大时长,该值与最大延迟有直接关系.因GOP缓冲\网络抖动\来电等因素引起的延迟,会根据该值的大小自动抛弃过期数据.建议1000-2000毫秒
    [_np setPlayerView:self.view];//设置视频播放视图
    [_np setContentMode:UIViewContentModeScaleAspectFit];//设置画面填充模式.
    [_np setHwEnable:YES];//设置开启硬解码,默认已开启,可以不调用.系统版本不支持或硬解码器初始化失败,自动转为软解.
    [_np setSubscribe:YES];
    //    [_np setConnArgs:@"S:info O:1 NS:uid:10012 NB:vip:1 NN:num:209.12 O:0"]; //类似ActionScript NetConnection.connect()时发送参数,rtmpdump风格
    //    [_np setRtspTransport:RTSP_TRANSPORT_TCP]; //设置rtsp使用TCP传输

    if (_videoURL && _videoURL.length>0){
        [_np setInputUrl:_videoURL]; //设置输入流地址,可以是RTMP/RTSP/HTTP-FLV/HLS等协议
        if (_playStatus) {
            [_np start];
        } else {
            [_np pause];
        }
        
        if (_autoPlay) {
            [_np start];
        }
    }
}

- (void) onEventCallback:(id)sender event:(int)event msg:(NSString *)msg {
    NSLog(@"onEventCallback:[%d] msg:%@",event,msg);
    switch (event) {
        case 1000:
            //开始连接播放流
            break;
        case 1001:
            //播放流连接成功
            [self fireEvent:@"start" params:@{@"start": @true, @"code":[NSNumber numberWithInt:event]}];
            break;
        case 1002:
            //播放流连接失败
            break;
        case 1003:
            //播放流连接失败或播放过程中网络异常断开,进入自动重连
            break;
        case 1004:
            //播放停止 所有资源处于可释放状态.
            break;
        case 1005:
             [self fireEvent:@"fail" params:nil];
            //播放中遇到网络异常
            break;
        case 1006:
            //连接超时或数据缓存为空超时
            break;
        case 1100:
            //NetStream.Buffer.Empty        数据缓冲为空 播放停止
            break;
        case 1101:
            //NetStream.Buffer.Buffering    开始缓冲数据
            break;
        case 1102:
            //NetStream.Buffer.Full         数据缓冲足够 开始播放
            [self fireEvent:@"start" params:nil];
            break;
        case 1103:
            [self fireEvent:@"finish" params:nil];
            //收到 Stream EOF 或者 NetStream.Play.UnpublishNotify
            break;
        case 1104:
            //获取到视频分辨率 width x height
            break;
        default:
            break;
    }
}
- (void)viewDidLoad
{
    [self initPlayer];
    [self controlVolume];
    [self setNetWorkStatus];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

-(void)setNetWorkStatus
{
    //开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.hostReachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.hostReachability startNotifier];
}
- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    if ([curReach isKindOfClass:[Reachability class]]) {
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        [self getNetworkStatus:netStatus];
    }
}
#pragma mark --   weex自定义 Method   ------
-(void)getNetworkStatus:(NetworkStatus)netStatus
{
    NSString *net = @"";
    switch (netStatus) {
        case NotReachable:
            net = @"ERROR";
            break;
        case ReachableViaWiFi:
            net = @"WIFI";
            break;
        case ReachableViaWWAN:
            net = @"MOBILE";
            break;
        default:
            break;
    }
    [self.weexInstance fireGlobalEvent:@"netStatus" params:@{@"net":net}];
}

- (void)viewWillUnload
{
    if(_np){
      [_np stop];//2.0版后该方法立即返回,不阻塞线程,也不需要再设置对象为 nil
    }
    _np = nil;
    _volumeSlider = nil;
    _mpVolumeView = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (self.hostReachability) {
        [self.hostReachability stopNotifier];
    }
    self.hostReachability = nil;
    if (false == _screenKeep) {
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    }
}


-(void)updateAttributes:(NSDictionary *)attributes
{
    if (attributes[@"src"]) {
        _videoURL = attributes[@"src"];
        [_np stop];
        if (_videoURL && _videoURL.length>0)
        {
            [_np setInputUrl:_videoURL];
        }
        if (_autoPlay) {
            [_np start];
        }
    }
    if (attributes[@"autoPlay"]) {
        _autoPlay = [attributes[@"autoPlay"] boolValue];
        [_np start];//开始播放
    }
    if ([attributes[@"playStatus"] compare:@"play" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        _playStatus = true;
        [_np start];//开始播放
        [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    }
    if ([attributes[@"playStatus"] compare:@"pause" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        _playStatus = false;
        [_np pause];//暂停播放
    }
    if ([attributes[@"playStatus"] compare:@"stop" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        _playStatus = false;
        [_np stop];//
    }
    if (attributes[@"poster"]) {
        _posterURL = attributes[@"poster"];
//        [_videoView setPosterURL:_posterURL];
    }
    
    if (attributes[@"screenKeepOn"]) {
        _screenKeep = [attributes[@"screenKeepOn"] boolValue];
    }
}

@end
